import HomeView from "@/views/HomeView.vue";
import { setting } from "@/config";
import { hasRole } from "@/utils/validate";

/**
 * 该方法用于转换后端返回的路由中的component
 * @returns
 */
export function convertRouter(routeList: any) {
  return routeList.map((route: any) => {
    if (route.component) {
      if (route.component === "HomeView") {
        route.component = HomeView;
      } else if (route.component.startsWith("@/views/")) {
        const path = route.component.slice(8);
        route.component = () => import(`@/views/${path}`);
      }
      route = convertRedirect(route, null, route.path);
    }
    if (route.children && route.children.length > 0) {
      route.children = convertRouter(route.children);
    }
    return route;
  });
}

/**
 * 路由角色过滤
 * @param myRole
 * @param routeList
 * @returns
 */
export function roleFilter(myRole: Array<string>, routeList: any) {
  return routeList.filter((route: any) => {
    if (hasRole(myRole, route.meta.role, setting.roleMode)) {
      if (route.children) {
        route.children = roleFilter(myRole, route.children);
      }
      return route;
    }
  });
}

/**
 * 路由外链过滤
 * @param routeList
 * @returns
 */
export function externalLinkFilter(routeList: any) {
  return routeList.filter((route: any) => {
    if (!route.meta.url) {
      if (route.children) {
        route.children = externalLinkFilter(route.children);
      }
      return route;
    }
  });
}

/**
 * 获取转换后并进行角色过滤后的路由
 * @param myRole
 * @param routeList
 * @returns
 */
export function getFilterRouter(myRole: Array<string>, routeList: any) {
  let router = convertRouter(routeList);
  router = roleFilter(myRole, router);
  if (!setting.externalLink) {
    router = externalLinkFilter(router);
  }
  return router;
}

/**
 * 该方法用于转换路由重定向
 * @param route
 * @param routeList
 * @param path
 * @returns
 */
export function convertRedirect(route: any, routeList: any, path: string) {
  if (route) {
    if (route.redirect) {
      route.redirect = path + "/" + route.redirect;
    }
    if (route.children) {
      route.children = convertRedirect(null, route.children, route.redirect);
    }
    return route;
  }
  if (routeList) {
    return routeList.filter((route: any) => {
      return convertRedirect(route, null, path);
    });
  }
}
